﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Jemgine.Animation
{
	public class AnimationPlayer
	{
		float rateSeconds;
		float totalElapsedSeconds;
		int frameCount;
		int currentFrame;
		bool Loop;

		public AnimationPlayer()
		{
			rateSeconds = 0.0f;
			totalElapsedSeconds = 0.0f;
			frameCount = 0;
			currentFrame = 0;
			Loop = false;
		}

		public void Play(float Rate, int Frames, bool Loop)
		{
			this.rateSeconds = 1.0f / Rate;
			this.frameCount = Frames;
			this.currentFrame = 0;
			this.totalElapsedSeconds = 0.0f;
			this.Loop = Loop;
		}

        public void HotPlay(float Rate, int Frames, bool Loop)
        {
            this.rateSeconds = 1.0f / Rate;
            this.frameCount = Frames;
            //this.currentFrame = 0;
            if (this.currentFrame >= Frames) this.currentFrame = 0;
            //this.totalElapsedSeconds = 0.0f;
            this.Loop = Loop;
        }

		public void Update(float elapsedSeconds)
		{
			totalElapsedSeconds += elapsedSeconds;
			if (totalElapsedSeconds >= rateSeconds)
			{
				totalElapsedSeconds -= rateSeconds;
				AdvanceFrame();
			}
		}

		private void AdvanceFrame()
		{
			if (currentFrame < (frameCount - 1)) ++currentFrame;
			else if (Loop) currentFrame = 0;
		}

		public int GetFrame() { return currentFrame; }
        public float GetFloatTime() { return (float)currentFrame + (totalElapsedSeconds / rateSeconds); }
	}
}
